import React, { useRef } from 'react';

import ProImageCanvas, { ProImageCanvasRef } from "vendor/components/pro-image-canvas";

export type { ProImageCanvasRef }

interface AiSnapshotDesc {
    DTime: string,
    CameraId: string,
    PicPath: string,
    ROIS: {
        ROIPoints: string,   // bbox坐标点, x1,y1;x2,y2;
        ROIMsg: string,      // 识别内容
        ROIScore: string,    // 值信度, 范围是0~1
        IsSecurity: string,  // 是否闯入安防区域: 0不是，1是
    }[],
}

interface AiSnapshotRenderProps{
    imageUrl: string;
    aiSnapshotDesc: string;
    style?: React.CSSProperties;
    labelStyle?: {
        fontSize ?: number,
    }
}

const AiSnapshotRender=  React.forwardRef<ProImageCanvasRef, AiSnapshotRenderProps>(({imageUrl, aiSnapshotDesc, style, labelStyle}, ref) => {
    // const proImageCanvasRef = useRef<ProImageCanvasRef>()
    let aiSnapshot: AiSnapshotDesc;
    let rois: AiSnapshotDesc["ROIS"] = []
    try {
        aiSnapshot = JSON.parse(aiSnapshotDesc) as AiSnapshotDesc;
        rois = aiSnapshot.ROIS
    }catch (e){
        // return <span>解析AI描述失败</span>
    }

    return <ProImageCanvas
        ref={ref}
        style={{borderRadius: 5, cursor: "pointer", ...style}}
        imageUrl={imageUrl}
        drawShapeData={rois.map(({ROIPoints, ROIMsg, ROIScore}) => {
            ROIPoints = ROIPoints.replace(/;$/, "");
            ROIMsg = ROIMsg.replace(">>","\n");

            return {
                label: ROIMsg,
                bbox: ROIPoints == "" ? [] : ROIPoints.split(";").map((item) => {
                    const itemArr = item.split(",")
                    return {
                        x: parseFloat(itemArr[0]),
                        y: parseFloat(itemArr[1]),
                    }
                }),
                labelStyle,
            }
        })}
    />
})

AiSnapshotRender.defaultProps = {
    labelStyle: {
        fontSize: 20,
    }
}

export default AiSnapshotRender;


interface AiSnapshotRenderBoxProps{
    imageUrl: string;
    box: string;
    style?: React.CSSProperties;
}

export const AiSnapshotRenderBox=  React.forwardRef<ProImageCanvasRef, AiSnapshotRenderBoxProps>(({imageUrl, box, style}, ref) => {
    return <ProImageCanvas
        ref={ref}
        style={{borderRadius: 5, cursor: "pointer", ...style}}
        imageUrl={imageUrl}
        drawShapeData={[{
            label: "",
            bbox: !box ? [] : box.split(";").map((item) => {
                const itemArr = item.split(",")
                return {
                    x: parseFloat(itemArr[0]),
                    y: parseFloat(itemArr[1]),
                }
            }),
        }]}
    />
})

